package org.yuanqiframework.yuanqi.boot.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.yuanqiframework.yuanqi.core.utils.StringUtils;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysRole;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysRoleUrl;
import org.yuanqiframework.yuanqi.boot.sys.mapper.SysRoleMapper;
import org.yuanqiframework.yuanqi.boot.sys.mapper.SysRoleUrlMapper;
import org.yuanqiframework.yuanqi.boot.sys.service.SysRoleService;
import org.yuanqiframework.yuanqi.boot.sys.vo.RoleVO;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @author cbt28
 * @description 针对表【sys_role】的数据库操作Service实现
 * @createDate 2025-07-19 15:34:16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleUrlMapper sysRoleUrlMapper;


    @Override
    public List<RoleVO> queryRoleVoList() {
        return sysRoleMapper.queryRoleVoList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addUrl(List<String> roleIds, List<String> urlIds) {
        List<SysRoleUrl> list = new LinkedList<>();
        urlIds.forEach(urlId -> {
            for (String roleId : roleIds) {
                SysRoleUrl sysRoleUrl = new SysRoleUrl();
                sysRoleUrl.setId(StringUtils.getUUID());
                sysRoleUrl.setRoleId(roleId);
                sysRoleUrl.setUrlId(urlId);
                list.add(sysRoleUrl);
            }
        });
        //判断数据库是否存在重复数据
        List<String> repeatIds = sysRoleUrlMapper.queryIds(list);
        if (repeatIds != null && !repeatIds.isEmpty()) {
            sysRoleUrlMapper.deleteByIds(repeatIds);
        }
        List<BatchResult> insert = sysRoleUrlMapper.insert(list);
        return insert.size();
    }

    @Override
    public int removeUrl(List<String> roleIds, List<String> urlIds) {
        List<SysRoleUrl> list = new LinkedList<>();
        urlIds.forEach(url -> {
            for (String roleId : roleIds) {
                SysRoleUrl sysRoleUrl = new SysRoleUrl();
                sysRoleUrl.setId(StringUtils.getUUID());
                sysRoleUrl.setRoleId(roleId);
                sysRoleUrl.setUrlId(url);
                list.add(sysRoleUrl);
            }
        });
        List<String> ids = sysRoleUrlMapper.queryIds(list);
        if (ids != null && !ids.isEmpty()) {
            return sysRoleUrlMapper.deleteByIds(ids);
        }
        return 0;
    }
}




